package lc20240428;

public class GetRainWater {
    public static void main(String[] args) {

        int[] nums = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(trap(nums));
    }

    public static int trap(int[] height) {
        int n = height.length;
        //找到每个柱子最左边柱子的最大值
        int[] Lmax = new int[n];
        int[] Rmax = new int[n];

        Lmax[0] = height[0];
        for (int i = 1; i < n; i++) {
            Lmax[i] = Math.max(Lmax[i - 1], height[i]);
        }

        //找到每个柱子最右边柱子的最大值
        Rmax[n - 1] = height[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            Rmax[i] = Math.max(height[i + 1], Rmax[i + 1]);
        }

        int sum = 0;
        for (int i = 1; i < n - 1; i++) {
            int temp = Math.min(Rmax[i], Lmax[i]) - height[i];
            if (temp > 0) {
                sum += temp;
            }
        }
        return sum;
    }
}
